﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using Jacaranda.Data;

namespace Jacaranda.Model
{
    public class StartsWithFunction : BinaryFunction
    {
        private int sequence;

        internal override string GenerateSql(Type propertyEntityType)
        {
            if (Operand2 is ConditionalExpression)
            {
                return string.Format("({0}) LIKE ({1} + '%')", Operand1.GenerateSql(propertyEntityType), (Operand2 as ConditionalExpression).GenerateSql(propertyEntityType));
            }
            else
            {
                string parameterName = "startsWith_Pattern" + ParameterIndex + "_" + sequence++;


                DbParameter parameter = DataAccess.Create().CreateDbParameter();

                parameter.ParameterName = parameterName;
                parameter.Value = Operand2.ToString();

                Command.Parameters.Add(parameter);

                return string.Format("{0} LIKE {1} + '%'", Operand1.GenerateSql(propertyEntityType), DataAccess.Create().CreateParameterizedExpression(parameterName));
            }
        }
    }
}
